package com.lh.bootswagger.service.impl;

import com.lh.bootswagger.entity.ApiInterface;
import com.lh.bootswagger.entity.ApiPermission;
import com.lh.bootswagger.entity.ApplyKey;
import com.lh.bootswagger.repository.ApiPermissionRepository;
import com.lh.bootswagger.service.JpaTestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lh
 * @Description: jpa查询练习
 * @date 2021/5/11 10:17
 */
@Service
public class JpaTestServiceImpl implements JpaTestService {
	@Autowired
	private ApiPermissionRepository apiPermissionRepository;

	@Override
	public List<ApiPermission> findApiPermission(String appId, String reqUrl) {
		Specification<ApiPermission> specification = new Specification<ApiPermission>() {
			@Override
			public Predicate toPredicate(Root<ApiPermission> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
				List<Predicate> list = new ArrayList<>();
				Join<ApplyKey, ApiPermission> join = root.join("applyKey", JoinType.LEFT);
				Join<ApiInterface, ApiPermission> join2 = root.join("apiInterface", JoinType.LEFT);

				if (null != appId) {
					list.add(criteriaBuilder.equal(join.get("appId"), appId));
				}

				if (null != reqUrl) {
					list.add(criteriaBuilder.equal(join2.get("requestUrl"), reqUrl));
				}

				Predicate[] p = new Predicate[list.size()];
				return criteriaBuilder.and(list.toArray(p));
			}
		};
		return apiPermissionRepository.findAll(specification);
	}
}
